package com.twh.www.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.twh.www.entity.WnCategory;
import com.twh.www.entity.WnGoods;
import com.twh.www.entity.WnUser;
import com.twh.www.service.WnCategoryService;
import com.twh.www.service.WnGoodsService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class    IndexController {

    @Autowired
    private WnGoodsService goodsService;
    @Autowired
    private WnCategoryService wnCategoryService;

    @RequestMapping("/")
    public String index(Model model, HttpSession session,
                        @RequestParam(defaultValue = "1") int pageNum,
                        @RequestParam(defaultValue = "7") int pageSize,
                        @RequestParam(value = "categoryId", required = false) Integer categoryId,
                        @RequestParam(required = false) String searchName) {
        String keyword = searchName;
        WnUser user = (WnUser) session.getAttribute("LoginUser");
        if (user == null) {
            return "redirect:/user/login";
        }
        // 查询所有类别
        List<WnCategory> categoryList = wnCategoryService.list();
        model.addAttribute("categoryList", categoryList);

        // 使用分页查询商品，支持模糊查询和分类查询
        Page<WnGoods> goodsPage;
        if (keyword != null && !keyword.trim().isEmpty()) {
            goodsPage = goodsService.searchGoodsByPage(keyword, pageNum, pageSize);
        } else if (categoryId != null) {
            goodsPage = goodsService.getGoodsByCategory(categoryId, pageNum, pageSize);
        } else {
            goodsPage = goodsService.getGoodsByPage(pageNum, pageSize);
        }

        List<WnGoods> hottest = goodsService.getHotGoods();

        // 将分页对象和商品列表添加到模型中
        model.addAttribute("goodsPage", goodsPage);
        model.addAttribute("goodsList", goodsPage.getRecords());
        model.addAttribute("hottest", hottest);
        if (keyword != null) {
            model.addAttribute("keyword", keyword); // 用于回显搜索关键词
        }

        return "index";
    }

}
